import javax.swing.JOptionPane;


abstract public class Handler {
	private Handler next;

	public Handler() {
		next = null;
	}
	public Handler(Handler n){ 
		next = n; 
	};

	public void process(int val){
		if (canHandle(val))
			handle(val);
		else if (next != null)
			next.process(val);
	}
	abstract void handle(int val);
	abstract boolean canHandle(int val);
}
class CompositeHandler extends Handler {
	private Handler[] children = new Handler[3];
	private int counter = 0;
	public CompositeHandler() {
		
		Handler EH = new EvenHandler();
		Handler OH = new OddHandler( EH );
		Handler PH = new PrimeHandler( OH );
		
		add(PH);
		add(OH);
		add(EH);
		
	}
	private void add(Handler h) {
		children[counter++] = h;
	}
	@Override
	public void process(int val){
		children[0].process(val);
	}
	@Override
	void handle(int val) {
		// TODO Auto-generated method stub
		children[0].handle(val);
	}
	@Override
	boolean canHandle(int val) {
		// TODO Auto-generated method stub
		return true;
	}
}
class PrimeHandler extends Handler {
	NetServerProxy srv = new NetServerProxy();
	
	public PrimeHandler(Handler OH) {
		super(OH);
	}
	@Override
	void handle(int val) {
		// TODO Auto-generated method stub
		JOptionPane.showMessageDialog(null, "The result computed from remote server is " + Integer.toString(srv.handle(val)) );
	}

	@Override
	boolean canHandle(int val) {
		// TODO Auto-generated method stub
		boolean result = true;
		for( int i = 2; i < val; ++i) {
			if(val%i == 0) {
				result = false;
				break;				
			}
		}
		return result & (val > 1);
	}
	
}
class OddHandler extends Handler {
	CachedNetServerProxy srv = new CachedNetServerProxy();
	public OddHandler(Handler EH) {
		// TODO Auto-generated constructor stub
		super( EH );
	}

	@Override
	void handle(int val) {
		// TODO Auto-generated method stub
		String result =  Integer.toString(srv.handle(val));
		String msg;
		boolean flag = srv.GetFlag();
		if(flag) {
			msg = "The result from the cached value is " + result;
		}
		else {
			msg = "The result computed from remote server is " + result;
		}
		JOptionPane.showMessageDialog(null,  msg);
	}

	@Override
	boolean canHandle(int val) {
		// TODO Auto-generated method stub
		return ( val%2 == 1 );
	}
	
}
class EvenHandler extends Handler {
	LocalServerProxy srv = new LocalServerProxy(new EvenServer());
	@Override
	void handle(int val) {
		// TODO Auto-generated method stub
		if( val % 6 != 0 ) {
			JOptionPane.showMessageDialog(null, "The result computed from local server is " + Integer.toString(srv.handle(val)) );
		}
		else {
			JOptionPane.showMessageDialog(null, "The request got rejected. Returning -1" );
		}
		
	}

	@Override
	boolean canHandle(int val) {
		// TODO Auto-generated method stub
		return ( val%2 == 0 );
	}
	
}